const Parse = require('parse/node');
const CabinetObj = Parse.Object.extend("AutoBorrow_Cabinets");
const GridObj = Parse.Object.extend("AutoBorrow_CabinetGrids");
const KindObj = Parse.Object.extend("AutoBorrow_Kinds");
const OperationLogObj = Parse.Object.extend("AutoBorrow_CabinetOperationLogs");
const TakeRecordObj = Parse.Object.extend("AutoBorrow_TakeRecords");
const ParseHelper = require('../helpers/parse');
const moment = require('moment');
const _ = require('lodash');

/**
 * 物料柜管理服务 - 增强版本
 * 支持多种规格柜子、实时通信、操作记录
 */

// 柜子状态
const CABINET_STATUS = {
    ONLINE: 'online',
    OFFLINE: 'offline',
    MAINTENANCE: 'maintenance',
    ERROR: 'error'
};

// 格子类型
const GRID_TYPES = {
    SMALL: 'small',
    MEDIUM: 'medium',
    LARGE: 'large'
};

// 格子状态
const GRID_STATUS = {
    EMPTY: 'empty',
    OCCUPIED: 'occupied',
    RESERVED: 'reserved',
    LOCKED: 'locked'
};

// 操作类型
const OPERATION_TYPES = {
    OPEN: 'open',
    CLOSE: 'close',
    STORE: 'store',
    TAKE: 'take',
    QUERY: 'query'
};

/**
 * 创建物料柜
 * @param {Object} cabinetData - 柜子数据
 * @returns {Promise<Object>} 创建结果
 */
async function createCabinet(cabinetData) {
    try {
        const cabinet = new CabinetObj();
        cabinet.set('name', cabinetData.name);
        cabinet.set('location', cabinetData.location || '');
        cabinet.set('description', cabinetData.description || '');
        cabinet.set('status', cabinetData.status);
        cabinet.set('HID', cabinetData.HID);
        cabinet.set('isActive', true);

        await cabinet.save(null, { useMasterKey: true });

        return {
            success: true,
            cabinet: ParseHelper.toJSON(cabinet),
            message: '物料柜创建成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 删除物料柜
 * @param {string} cabinetId - 柜子数据
 * @returns {Promise<Object>} 删除结果
 */

async function deleteCabinet(cabinetId) {
    try {
        const cabinetQuery = new Parse.Query(CabinetObj);
        cabinetQuery.equalTo('objectId', cabinetId);
        const cabinet = await cabinetQuery.first({ useMasterKey: true });

        if (!cabinet) {
            return {
                success: false,
                error: '物料柜不存在'
            };
        }

        // 标记为已删除
        cabinet.set('isDeleted', true);
        await cabinet.save(null, { useMasterKey: true });

        return {
            success: true,
            message: '物料柜已删除'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}
/**
 * 更新物料柜
 * @param {string} cabinetId - 柜子数据
 * @param {Object} updateData - 更新数据
 * @returns {Promise<Object>} 更新结果
 */
async function updateCabinet(cabinetId, updateData) {
    try {
        const cabinetQuery = new Parse.Query(CabinetObj);
        cabinetQuery.equalTo('objectId', cabinetId);
        const cabinet = await cabinetQuery.first({ useMasterKey: true });

        if (!cabinet) {
            return {
                success: false,
                error: '物料柜不存在'
            };
        }

        // 更新柜子信息
        if (updateData.name !== undefined) {
            cabinet.set('name', updateData.name);
        }
        if (updateData.location !== undefined) {
            cabinet.set('location', updateData.location);
        }
        if (updateData.description !== undefined) {
            cabinet.set('description', updateData.description);
        }
        if (updateData.status !== undefined) {
            cabinet.set('status', updateData.status);
        }
        if (updateData.HID !== undefined) {
            cabinet.set('HID', updateData.HID);
        }

        await cabinet.save(null, { useMasterKey: true });

        return {
            success: true,
            cabinet: ParseHelper.toJSON(cabinet),
            message: '物料柜更新成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 为柜子创建格子
 * @param {string} cabinetId - 柜子ID
 * @param {Object} gridConfig - 格子配置
 * @returns {Promise<Object>} 创建结果
 */
async function createGridsForCabinet(cabinetId, gridConfig) {
    try {
        const grids = [];
        
        // 创建不同类型的格子
        for (const [gridType, config] of Object.entries(gridConfig)) {
            const { count, boards } = config;
            
            for (let boardIndex = 0; boardIndex < boards.length; boardIndex++) {
                const boardId = boards[boardIndex];
                
                for (let gridIndex = 1; gridIndex <= count; gridIndex++) {
                    const grid = new GridObj();
                    grid.set('cabinetId', cabinetId);
                    grid.set('cid', boardId.toString());
                    grid.set('number', gridIndex);
                    grid.set('type', gridType);
                    grid.set('status', GRID_STATUS.EMPTY);
                    grid.set('materialId', null);
                    grid.set('materialCount', 0);
                    grid.set('isActive', true);
                    grid.set('createdAt', new Date());
                    
                    grids.push(grid);
                }
            }
        }
        
        await Parse.Object.saveAll(grids, { useMasterKey: true });
        
        return {
            success: true,
            message: `成功创建 ${grids.length} 个格子`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取柜子信息
 * @param {string} cabinetId - 柜子ID
 * @returns {Promise<Object>} 柜子信息
 */
async function getCabinetInfo(cabinetId) {
    try {
        const cabinetQuery = new Parse.Query(CabinetObj);
        cabinetQuery.equalTo('cabinetId', cabinetId);
        cabinetQuery.notEqualTo('isDeleted', true);
        
        const cabinet = await cabinetQuery.first({ useMasterKey: true });
        if (!cabinet) {
            throw new Error('柜子不存在');
        }
        
        // 获取格子信息
        const gridQuery = new Parse.Query(GridObj);
        gridQuery.equalTo('cabinetId', cabinetId);
        gridQuery.equalTo('isActive', true);
        gridQuery.ascending('cid');
        gridQuery.ascending('number');
        
        const grids = await gridQuery.find({ useMasterKey: true });
        
        const cabinetData = ParseHelper.toJSON(cabinet);
        cabinetData.grids = grids.map(grid => ParseHelper.toJSON(grid));
        
        return {
            success: true,
            cabinet: cabinetData
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

async function getKindsByIds(kindIds) {
    try {
        if (!kindIds || kindIds.length === 0) {
            return [];
        }
        
        const query = new Parse.Query(KindObj);
        query.containedIn('objectId', kindIds);
        
        const kinds = await query.find({ useMasterKey: true });
        return ParseHelper.toJSONList(kinds);
    } catch (error) {
        console.error('获取物料种类失败:', error);
        return [];
    }
}

/**
 * 获取物料柜格子列表
 * @param {string} cabinetId - 物料柜ID
 * @returns {Promise<Object>} 格子列表
 */
async function getCabinetSlots(cabinetId) {
    try {
        const query = new Parse.Query(GridObj);
        query.equalTo('cabinetId', cabinetId);
        query.ascending('position');
        query.limit(1000); // 限制查询结果数量，避免一次性加载过多数据
        const slots = await query.find({ useMasterKey: true });
        const slotData = ParseHelper.toJSONList(slots);
        const kindIds=slotData.map(slot => slot.kindId);
        const kinds = await getKindsByIds(kindIds);
        const kindMap = _.keyBy(kinds, 'objectId');
        return {
            success: true,
            slots: slotData.map(slot => {
                const kind = kindMap[slot.kindId] || {};
                return {
                    id: slot.objectId,
                    number: slot.number || slot.position,
                    kind,
                    count: slot.count || 0,
                    boardNumber: slot.boardNumber,
                    size: slot.size || 'medium',
                    status: slot.status || 'empty',
                    isEnabled: slot.isEnabled !== false,
                    cid: slot.cid,
                    description: slot.description || ''
                };
            })
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取物料柜信息
 * @param {string} cabinetId - 物料柜ID
 * @returns {Promise<Object>} 物料柜信息
 */
async function getCabinetById(cabinetId) {
    try {
        const query = new Parse.Query(CabinetObj);
        query.equalTo('objectId', cabinetId);
        
        const cabinet = await query.first({ useMasterKey: true });
        
        if (!cabinet) {
            return {
                success: false,
                error: '物料柜不存在'
            };
        }
        
        return {
            success: true,
            cabinet: ParseHelper.toJSON(cabinet)
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 更新格子信息
 * @param {string} cabinetId - 物料柜ID
 * @param {string} slotId - 格子ID
 * @param {Object} updateData - 更新数据
 * @returns {Promise<Object>} 更新结果
 */
async function updateSlot(cabinetId, slotId, updateData) {
    try {
        const query = new Parse.Query(GridObj);
        query.equalTo('objectId', slotId);
        query.equalTo('cabinetId', cabinetId);
        
        const slot = await query.first({ useMasterKey: true });
        
        if (!slot) {
            return {
                success: false,
                error: '格子不存在'
            };
        }
        
        // 更新格子信息
        if (updateData.number !== undefined) {
            slot.set('number', updateData.number);
        }
        if (updateData.boardNumber !== undefined) {
            slot.set('boardNumber', updateData.boardNumber);
        }
        if (updateData.size !== undefined) {
            slot.set('size', updateData.size);
        }
        if (updateData.status !== undefined) {
            slot.set('status', updateData.status);
        }
        if (updateData.position !== undefined) {
            slot.set('position', updateData.position);
        }
        if (updateData.isEnabled !== undefined) {
            slot.set('isEnabled', updateData.isEnabled);
        }
        if (updateData.description !== undefined) {
            slot.set('description', updateData.description);
        }
        
        slot.set('updatedAt', new Date());
        
        await slot.save(null, { useMasterKey: true });
        
        return {
            success: true,
            slot: ParseHelper.toJSON(slot)
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 创建新格子
 * @param {string} cabinetId - 物料柜ID
 * @param {Object} slotData - 格子数据
 * @returns {Promise<Object>} 创建结果
 */
async function createSlot(cabinetId, slotData) {
    try {
        const slot = new GridObj();
        slot.set('cabinetId', cabinetId);
        slot.set('number', slotData.number);
        slot.set('boardNumber', slotData.boardNumber);
        slot.set('cid', slotData.cid);
        slot.set('size', slotData.size || 'medium');
        slot.set('status', slotData.status || 'empty');
        slot.set('isEnabled', slotData.isEnabled !== false);
        slot.set('description', slotData.description || '');
        
        await slot.save(null, { useMasterKey: true });
        
        return {
            success: true,
            slot: ParseHelper.toJSON(slot)
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 删除格子
 * @param {string} cabinetId - 物料柜ID
 * @param {string} slotId - 格子ID
 * @returns {Promise<Object>} 删除结果
 */
async function deleteSlot(cabinetId, slotId) {
    try {
        const query = new Parse.Query(GridObj);
        query.equalTo('objectId', slotId);
        query.equalTo('cabinetId', cabinetId);
        
        const slot = await query.first({ useMasterKey: true });
        
        if (!slot) {
            return {
                success: false,
                error: '格子不存在'
            };
        }
        
        await slot.destroy({ useMasterKey: true });
        
        return {
            success: true,
            message: '格子删除成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 批量创建格子
 * @param {string} cabinetId - 物料柜ID
 * @param {Object} config - 批量配置
 * @returns {Promise<Object>} 创建结果
 */
async function batchCreateSlots(cabinetId, config) {
    try {
        const { boardCount, cellsPerBoard, defaultSize, startNumber, startBoardNumber = 1 } = config;
        const slots = [];
        
        let currentNumber = startNumber;
        
        for (let boardIndex = 0; boardIndex < boardCount; boardIndex++) {
            const actualBoardNum = startBoardNumber + boardIndex;
            
            for (let cellNum = 1; cellNum <= cellsPerBoard; cellNum++) {
                const slot = new GridObj();
                slot.set('cabinetId', cabinetId);
                slot.set('number', currentNumber);
                slot.set('boardNumber', cellNum);
                slot.set('cid', actualBoardNum);
                slot.set('size', defaultSize);
                slot.set('status', 'empty');
                slot.set('isEnabled', true);
                slot.set('description', `控制板${actualBoardNum}-格子${cellNum}`);
                
                slots.push(slot);
                currentNumber++;
            }
        }
        
        await Parse.Object.saveAll(slots, { useMasterKey: true });
        
        return {
            success: true,
            message: `成功创建 ${slots.length} 个格子`,
            count: slots.length
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 批量删除格子
 * @param {string} cabinetId - 物料柜ID
 * @param {Array} slotIds - 要删除的格子ID数组
 * @returns {Promise<Object>} 删除结果
 */
async function batchDeleteSlots(cabinetId, slotIds) {
    try {
        if (!slotIds || slotIds.length === 0) {
            return {
                success: false,
                error: '请提供要删除的格子ID'
            };
        }

        const query = new Parse.Query(GridObj);
        query.equalTo('cabinetId', cabinetId);
        query.containedIn('objectId', slotIds);
        
        const slots = await query.find({ useMasterKey: true });
        
        if (slots.length === 0) {
            return {
                success: false,
                error: '没有找到要删除的格子'
            };
        }

        // 检查是否有格子正在使用中
        const occupiedSlots = slots.filter(slot => slot.get('status') === 'occupied');
        if (occupiedSlots.length > 0) {
            return {
                success: false,
                error: `有 ${occupiedSlots.length} 个格子正在使用中，无法删除`
            };
        }

        await Parse.Object.destroyAll(slots, { useMasterKey: true });
        
        return {
            success: true,
            message: `成功删除 ${slots.length} 个格子`,
            count: slots.length
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取空闲格子
 * @param {string} cabinetId - 柜子ID
 * @param {string} gridType - 格子类型
 * @returns {Promise<Object>} 空闲格子信息
 */
async function getEmptyGrid(cabinetId, gridType = null) {
    try {
        const query = new Parse.Query(GridObj);
        query.equalTo('cabinetId', cabinetId);
        query.equalTo('status', GRID_STATUS.EMPTY);
        query.equalTo('isActive', true);
        
        if (gridType) {
            query.equalTo('type', gridType);
        }
        
        query.ascending('cid');
        query.ascending('number');
        
        const grid = await query.first({ useMasterKey: true });
        
        if (!grid) {
            return {
                success: false,
                error: '没有可用的空闲格子'
            };
        }
        
        return {
            success: true,
            grid: ParseHelper.toJSON(grid)
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 存储物料到格子
 * @param {Object} storeData - 存储数据
 * @returns {Promise<Object>} 存储结果
 */
async function storeMaterialToGrid(storeData) {
    try {
        const {
            cabinetId,
            gridId,
            materialId,
            materialCount,
            operatorId
        } = storeData;
        
        // 更新格子状态
        const grid = GridObj.createWithoutData(gridId);
        grid.set('status', GRID_STATUS.OCCUPIED);
        grid.set('materialId', materialId);
        grid.set('materialCount', materialCount);
        grid.set('updatedAt', new Date());
        
        await grid.save(null, { useMasterKey: true });
        
        // 记录操作日志
        await logCabinetOperation({
            cabinetId,
            gridId,
            operatorId,
            operationType: OPERATION_TYPES.STORE,
            materialId,
            materialCount,
            description: '物料上架'
        });
        
        return {
            success: true,
            message: '物料存储成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 从格子取出物料
 * @param {Object} takeData - 取出数据
 * @returns {Promise<Object>} 取出结果
 */
async function takeMaterialFromGrid(takeData) {
    try {
        const {
            cabinetId,
            gridId,
            takeCount,
            operatorId
        } = takeData;
        
        // 获取格子信息
        const gridQuery = new Parse.Query(GridObj);
        const grid = await gridQuery.get(gridId, { useMasterKey: true });
        
        if (!grid) {
            throw new Error('格子不存在');
        }
        
        const currentCount = grid.get('materialCount') || 0;
        const materialId = grid.get('materialId');
        
        if (currentCount < takeCount) {
            throw new Error('格子中的物料数量不足');
        }
        
        // 更新格子状态
        const newCount = currentCount - takeCount;
        grid.set('materialCount', newCount);
        
        if (newCount === 0) {
            grid.set('status', GRID_STATUS.EMPTY);
            grid.set('materialId', null);
        }
        
        grid.set('updatedAt', new Date());
        await grid.save(null, { useMasterKey: true });
        
        // 记录操作日志
        await logCabinetOperation({
            cabinetId,
            gridId,
            operatorId,
            operationType: OPERATION_TYPES.TAKE,
            materialId,
            materialCount: takeCount,
            description: '物料取出'
        });
        
        // 记录取出记录
        await recordTakeOperation({
            cabinetId,
            gridId,
            materialId,
            takeCount,
            operatorId
        });
        
        return {
            success: true,
            message: '物料取出成功'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 控制柜门开关
 * @param {Object} controlData - 控制数据
 * @returns {Promise<Object>} 控制结果
 */
async function controlCabinetDoor(controlData) {
    try {
        const {
            cabinetId,
            boardId,
            portId,
            operation, // 'open' or 'close'
            operatorId
        } = controlData;
        
        // 获取柜子信息
        const cabinetQuery = new Parse.Query(CabinetObj);
        cabinetQuery.equalTo('cabinetId', cabinetId);
        const cabinet = await cabinetQuery.first({ useMasterKey: true });
        
        if (!cabinet) {
            throw new Error('柜子不存在');
        }
        
        // 发送控制指令
        const controlMessage = {
            type: operation,
            lockerid: cabinetId,
            boardid: parseInt(boardId),
            portid: parseInt(portId),
            cmd: 'server'
        };
        
        // 这里需要实现WebSocket通信
        // const result = await sendControlMessage(cabinet, controlMessage);
        
        // 记录操作日志
        await logCabinetOperation({
            cabinetId,
            gridId: null,
            operatorId,
            operationType: operation === 'open' ? OPERATION_TYPES.OPEN : OPERATION_TYPES.CLOSE,
            description: `${operation === 'open' ? '开启' : '关闭'}柜门 - 板${boardId}端口${portId}`
        });
        
        return {
            success: true,
            message: `柜门${operation === 'open' ? '开启' : '关闭'}指令已发送`
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 查询柜门状态
 * @param {Object} queryData - 查询数据
 * @returns {Promise<Object>} 查询结果
 */
async function queryCabinetDoorStatus(queryData) {
    try {
        const {
            cabinetId,
            boardId,
            portId
        } = queryData;
        
        // 获取柜子信息
        const cabinetQuery = new Parse.Query(CabinetObj);
        cabinetQuery.equalTo('cabinetId', cabinetId);
        const cabinet = await cabinetQuery.first({ useMasterKey: true });
        
        if (!cabinet) {
            throw new Error('柜子不存在');
        }
        
        // 发送查询指令
        const queryMessage = {
            type: 'query',
            lockerid: cabinetId,
            boardid: parseInt(boardId),
            portid: parseInt(portId),
            cmd: 'server'
        };
        
        // 这里需要实现WebSocket通信
        // const result = await sendQueryMessage(cabinet, queryMessage);
        
        return {
            success: true,
            message: '状态查询指令已发送'
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 记录柜子操作日志
 * @param {Object} logData - 日志数据
 * @returns {Promise<void>}
 */
async function logCabinetOperation(logData) {
    try {
        const log = new OperationLogObj();
        log.set('cabinetId', logData.cabinetId);
        log.set('gridId', logData.gridId);
        log.set('operatorId', logData.operatorId);
        log.set('operationType', logData.operationType);
        log.set('materialId', logData.materialId);
        log.set('materialCount', logData.materialCount);
        log.set('description', logData.description);
        log.set('createdAt', new Date());
        
        await log.save(null, { useMasterKey: true });
    } catch (error) {
        console.error('记录操作日志失败:', error);
    }
}

/**
 * 记录取出操作
 * @param {Object} recordData - 记录数据
 * @returns {Promise<void>}
 */
async function recordTakeOperation(recordData) {
    try {
        const record = new TakeRecordObj();
        record.set('cabinetId', recordData.cabinetId);
        record.set('gridId', recordData.gridId);
        record.set('materialId', recordData.materialId);
        record.set('takeCount', recordData.takeCount);
        record.set('operatorId', recordData.operatorId);
        record.set('createdAt', new Date());
        
        await record.save(null, { useMasterKey: true });
    } catch (error) {
        console.error('记录取出操作失败:', error);
    }
}

/**
 * 获取柜子使用统计
 * @param {string} cabinetId - 柜子ID
 * @param {Object} options - 统计选项
 * @returns {Promise<Object>} 统计结果
 */
async function getCabinetUsageStats(cabinetId, options = {}) {
    try {
        const {
            startDate = moment().startOf('month').toDate(),
            endDate = moment().endOf('month').toDate()
        } = options;
        
        // 获取操作日志统计
        const logQuery = new Parse.Query(OperationLogObj);
        logQuery.equalTo('cabinetId', cabinetId);
        logQuery.greaterThanOrEqualTo('createdAt', startDate);
        logQuery.lessThanOrEqualTo('createdAt', endDate);
        
        const logs = await logQuery.find({ useMasterKey: true });
        
        const stats = {
            totalOperations: logs.length,
            operationsByType: {},
            operationsByDate: {},
            operationsByHour: {}
        };
        
        logs.forEach(log => {
            const logData = ParseHelper.toJSON(log);
            const operationType = logData.operationType;
            const date = moment(logData.createdAt).format('YYYY-MM-DD');
            const hour = moment(logData.createdAt).format('HH');
            
            // 按类型统计
            if (!stats.operationsByType[operationType]) {
                stats.operationsByType[operationType] = 0;
            }
            stats.operationsByType[operationType]++;
            
            // 按日期统计
            if (!stats.operationsByDate[date]) {
                stats.operationsByDate[date] = 0;
            }
            stats.operationsByDate[date]++;
            
            // 按小时统计
            if (!stats.operationsByHour[hour]) {
                stats.operationsByHour[hour] = 0;
            }
            stats.operationsByHour[hour]++;
        });
        
        return {
            success: true,
            stats
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取物料柜统计数据
 * @returns {Promise<Object>} 统计结果
 */
async function getCabinetStats() {
    try {
        // 获取所有柜子
        const cabinetQuery = new Parse.Query(CabinetObj);
        cabinetQuery.notEqualTo('isDeleted', true);
        
        const cabinets = await cabinetQuery.find({ useMasterKey: true });
        
        const total = cabinets.length;
        let active = 0;
        let offline = 0;
        
        // 统计在线和离线设备
        cabinets.forEach(cabinet => {
            const status = cabinet.get('status');
            if (status === "active") {
                active++;
            } else if (status === "offline" || status === "maintenance" || status === "error") {
                offline++;
            }
        });
        
        // 获取格子使用率统计
        const gridQuery = new Parse.Query(GridObj);
        gridQuery.limit(9999); // 限制查询结果数量，避免一次性加载过多数据
        const allGrids = await gridQuery.find({ useMasterKey: true });
        
        const totalGrids = allGrids.length;
        let occupiedGrids = 0;
        let maintenanceGrids = 0; // 维修中格子
        
        allGrids.forEach(grid => {
            const status = grid.get('status');
            if (status === "occupied") {
                occupiedGrids++;
            }
            if (status === "maintenance") {
                maintenanceGrids++; // 维修中格子
            }
        });
        
        const occupancyRate = totalGrids > 0 ? (((occupiedGrids+maintenanceGrids )/ totalGrids) * 100).toFixed(2) : 0;
        
        return {
            success: true,
            data: {
                total,
                active,
                offline,
                cellStats: {
                    totalCells: totalGrids,
                    occupiedCells: occupiedGrids,
                    maintenanceGrids: maintenanceGrids,
                    availableCells: totalGrids - occupiedGrids - maintenanceGrids,
                    occupancyRate: parseFloat(occupancyRate)
                }
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}

/**
 * 获取柜子列表
 * @param {Object} options - 查询选项
 * @returns {Promise<Object>} 柜子列表
 */
async function getCabinetList(options = {}) {
    try {
        const {
            status,
            location,
            page = 1,
            limit = 10,
            search = ''
        } = options;
        
        const query = new Parse.Query(CabinetObj);
        query.notEqualTo('isDeleted', true);
        console.log('获取柜子列表', { status, location, search, page, limit });
        if (status) {
            query.equalTo('status', status);
        }
        
        if (location) {
            query.contains('location', location);
        }
        if (search) {
            query.contains('name', search);
        }
        
        query.descending('createdAt');
        
        const skip = (page - 1) * limit;
        query.skip(skip);
        query.limit(limit);
        
        const [cabinets, total] = await Promise.all([
            query.find({ useMasterKey: true }),
            query.count({ useMasterKey: true })
        ]);
        
        // 获取每个柜子的格子占用信息
        const cabinetsWithStats = await Promise.all(
            cabinets.map(async (cabinet) => {
                const cabinetData = ParseHelper.toJSON(cabinet);
                
                // 查询该柜子的所有格子
                const gridQuery = new Parse.Query(GridObj);
                gridQuery.limit(999);
                gridQuery.equalTo('cabinetId', cabinetData.objectId);
                const allGrids = await gridQuery.find({ useMasterKey: true }).then(ParseHelper.toJSONList);
                // 查询该柜子中被占用的格子
                const occupiedGrids = allGrids.filter(grid => grid.status === "occupied");
                // const [allGrids, occupiedGrids] = await Promise.all([
                //     gridQuery.find({ useMasterKey: true }),
                //     gridQuery.equalTo('status', 'occupied').find({ useMasterKey: true })
                // ]);
                // console.log('获取柜子格子信息', allGrids, occupiedGrids);
                
                // 计算占用率
                const totalCells = allGrids.length;
                const occupiedCells = occupiedGrids.length;
                const occupancyRate = totalCells > 0 ? Math.round((occupiedCells / totalCells) * 100) : 0;
                
                return {
                    ...cabinetData,
                    totalCells,
                    occupiedCells,
                    availableCells: totalCells - occupiedCells,
                    occupancyRate
                };
            })
        );
        
        return {
            success: true,
            cabinets: cabinetsWithStats,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return {
            success: false,
            error: error.message
        };
    }
}
async function getGridById(gridId) {
        const query = new Parse.Query(GridObj);
        query.equalTo('objectId', gridId);
        const grid = await query.first({ useMasterKey: true });
        return ParseHelper.toJSON(grid)
        
  
}

module.exports = {
    createCabinet,
    createGridsForCabinet,
    getCabinetInfo,
    getCabinetById,
    getCabinetSlots,
    createSlot,
    updateSlot,
    deleteSlot,
    batchCreateSlots,
    batchDeleteSlots,
    getEmptyGrid,
    storeMaterialToGrid,
    takeMaterialFromGrid,
    controlCabinetDoor,
    queryCabinetDoorStatus,
    logCabinetOperation,
    recordTakeOperation,
    getCabinetUsageStats,
    getCabinetStats,
    getCabinetList,
    deleteCabinet,
    updateCabinet,
    getGridById,
    CABINET_STATUS,
    GRID_TYPES,
    GRID_STATUS,
    OPERATION_TYPES
};
